<script setup>
import PostList from '@/components/PostList.vue'
import '@/assets/main.css'
import FabButton from '@/components/FabButton.vue'
import { ref, onMounted, nextTick } from 'vue'
import api from '@/services/api'

// 生成虚拟帖子数据
const posts = Array.from({ length: 14 }).map((_, i) => ({
  id: i + 1,
  userId: 100 + i,
  avatar: 'https://api.dicebear.com/7.x/miniavs/svg?seed=' + (i + 1),
  nickname: '用户' + (i + 1),
  time: '2小时前',
  content: '这是一个测试帖子内容，欢迎体验本平台！',
  likes: Math.floor(Math.random() * 100),
  comments: Math.floor(Math.random() * 30),
}))

const dynamicPosts = ref([])
const sortType = ref(1) // 1=最热，2=最新
const page = ref(1)
const pageSize = 10
const hasMore = ref(true)
const loading = ref(false)
const total = ref(0)

// 自动加载更多逻辑
function handleScroll() {
  if (!hasMore.value || loading.value) return
  const scrollY = window.scrollY || window.pageYOffset
  const vh = window.innerHeight
  const docH = document.documentElement.scrollHeight
  if (docH - (scrollY + vh) < vh * 0.2) {
    // 离底部20vh自动加载
    fetchPosts(sortType.value, page.value + 1)
  }
}

// 判断内容是否不满一屏
function isContentShort() {
  return document.documentElement.scrollHeight <= window.innerHeight + 10
}

async function fetchPosts(sort = 1, nextPage = 1, reset = false) {
  loading.value = true
  try {
    const res = await api.fetchPosts({ page: nextPage, size: pageSize, sort })
    if (res.data && res.data.code === 0) {
      const newPosts = res.data.data.posts.map((item) => ({
        id: item.id,
        userId: item.userId,
        avatar: item.userPhoto,
        nickname: item.userNickname,
        time: item.addTime,
        content: item.content,
        likes: item.likeCount,
        comments: item.commentCount,
      }))
      if (reset) {
        dynamicPosts.value = newPosts
        page.value = 1
      } else {
        // 合并去重
        const ids = new Set(dynamicPosts.value.map((p) => p.id))
        dynamicPosts.value.push(...newPosts.filter((p) => !ids.has(p.id)))
        page.value = nextPage
      }
      total.value = res.data.data.total || 0
      // 判断是否还有更多
      hasMore.value = dynamicPosts.value.length < total.value
    } else {
      console.warn('[帖子获取] 后端返回异常：', res.data)
    }
  } catch (e) {
    console.error('[帖子获取] 请求失败：', e && (e.message || e))
  } finally {
    loading.value = false
  }
}

onMounted(async () => {
  await fetchPosts(sortType.value, 1, true)
  await nextTick()
  // 如果内容不满一屏且还有更多，自动加载
  if (isContentShort() && hasMore.value) {
    fetchPosts(sortType.value, page.value + 1)
  }
  window.addEventListener('scroll', handleScroll)
})

// 组件卸载时移除监听
import { onUnmounted } from 'vue'
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})

function handleSortChange(type) {
  if (sortType.value !== type) {
    sortType.value = type
    fetchPosts(type, 1, true)
  }
}

function handleLoadMore() {
  if (hasMore.value && !loading.value) {
    fetchPosts(sortType.value, page.value + 1)
  }
}
</script>

<template>
  <div class="main-layout">
    <div class="main-content">
      <div class="sort-bar">
        <button :class="['sort-btn', { active: sortType === 1 }]" @click="handleSortChange(1)">
          最热
        </button>
        <button :class="['sort-btn', { active: sortType === 2 }]" @click="handleSortChange(2)">
          最新
        </button>
      </div>
      <PostList :posts="dynamicPosts.length ? dynamicPosts : posts" />
      <div v-if="!loading && hasMore && isContentShort()" class="load-more-bar">
        <button class="load-more-btn" @click="handleLoadMore">加载更多</button>
      </div>
      <div v-if="!hasMore && dynamicPosts.length" class="no-more">没有更多了</div>
      <div v-if="loading" class="loading-bar">加载中...</div>
    </div>
    <FabButton />
  </div>
</template>

<style scoped>
.main-layout {
  display: flex;
  flex-direction: column;
  align-items: center;
  min-height: 100vh;
  background: var(--color-bg);
}
.main-content {
  width: 100%;
  min-height: 100vh;
  margin: 0 auto;
  background: var(--color-input-bg);
  border-radius: 0.5rem;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.04);
  padding: 2rem 1.5rem 2.5rem 1.5rem;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}
.sort-bar {
  display: flex;
  gap: 1.2rem;
  margin-bottom: 1.2rem;
  justify-content: flex-end;
}
.sort-btn {
  background: var(--color-surface, var(--color-input-bg));
  color: var(--color-primary);
  border: 1.5px solid var(--color-primary);
  border-radius: 0.5rem;
  padding: 0.4rem 1.2rem;
  font-size: 1.08rem;
  font-weight: 500;
  cursor: pointer;
  transition:
    background 0.2s,
    color 0.2s,
    border 0.2s;
}
.sort-btn.active {
  background: var(--color-primary);
  color: var(--color-button-text);
  border-color: var(--color-primary);
}
.sort-btn:hover:not(.active) {
  background: var(--color-primary-hover);
  color: var(--color-button-text);
}
.load-more-bar {
  display: flex;
  justify-content: center;
  margin: 1.5rem 0 0.5rem 0;
}
.load-more-btn {
  background: var(--color-primary);
  color: var(--color-button-text);
  border: none;
  border-radius: 0.5rem;
  padding: 0.7rem 2.2rem;
  font-size: 1.1rem;
  font-weight: 600;
  cursor: pointer;
  box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.08);
  transition: background 0.2s;
}
.load-more-btn:hover:not(:disabled) {
  background: var(--color-primary-hover);
}
.no-more {
  text-align: center;
  color: var(--color-text-secondary);
  font-size: 1.08rem;
  margin: 1.2rem 0 0.5rem 0;
}
.loading-bar {
  text-align: center;
  color: var(--color-primary);
  font-size: 1.08rem;
  margin: 1.2rem 0 0.5rem 0;
}
</style>
